import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score

# 加载数据集
file_path = r"C:\Users\HYHPlayer_MHS\Documents\WeChat Files\wxid_5fx1qyfws5wv12\FileStorage\File\2024-07\house.csv"
house_data = pd.read_csv(file_path, encoding='latin1')

# 删除缺失值超过20%的列
columns_to_drop = ['½¨Öþ½á¹¹', '×¡Õ¬Àà±ð', '½¨ÖþÀà±ð']
house_data_cleaned = house_data.drop(columns=columns_to_drop)

# 用最常见值填充分类列的缺失值
house_data_cleaned['½¨ÖþÄê´ú'].fillna(house_data_cleaned['½¨ÖþÄê´ú'].mode()[0], inplace=True)
house_data_cleaned['µçÌÝ'].fillna(house_data_cleaned['µçÌÝ'].mode()[0], inplace=True)
house_data_cleaned['²úÈ¨ÐÔÖÊ'].fillna(house_data_cleaned['²úÈ¨ÐÔÖÊ'].mode()[0], inplace=True)

# 将'½¨ÖþÃæ»ý'转换为数值
house_data_cleaned['½¨ÖþÃæ»ý'] = house_data_cleaned['½¨ÖþÃæ»ý'].str.extract('(\d+.\d+)').astype(float)

# 用中位数填充'½¨ÖþÃæ»ý'的缺失值
house_data_cleaned['½¨ÖþÃæ»ý'].fillna(house_data_cleaned['½¨ÖþÃæ»ý'].median(), inplace=True)

# 将'µ¥¼Û'转换为数值，去除非数字字符并转换为浮点数
house_data_cleaned['µ¥¼Û'] = house_data_cleaned['µ¥¼Û'].str.replace('Ôª/Æ½Ã×', '').astype(float)

# 对分类列进行独热编码
house_data_encoded = pd.get_dummies(house_data_cleaned,
                                    columns=['»§ÐÍ', '³¯Ïò', 'Â¥²ã', '×°ÐÞ', '½¨ÖþÄê´ú', 'µçÌÝ', '²úÈ¨ÐÔÖÊ', 'ÇøÓò'])

# 定义特征和目标变量
X = house_data_encoded.drop(columns=['×Ü¼Û'])
y = house_data_encoded['×Ü¼Û']

# 将数据集划分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 初始化并训练线性回归模型
model = LinearRegression()
model.fit(X_train, y_train)

# 在测试集上进行预测
y_pred = model.predict(X_test)

# 评估模型
mae = mean_absolute_error(y_test, y_pred)
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)

print(f'平均绝对误差: {mae}')
print(f'均方误差: {mse}')
print(f'决定系数: {r2}')


# 定义预测函数
def predict_price(model, input_data):
    input_df = pd.DataFrame([input_data])
    input_df_encoded = pd.get_dummies(input_df)

    # 添加缺失的列
    input_df_encoded = pd.concat([input_df_encoded, pd.DataFrame(columns=X_train.columns)]).fillna(0)

    # 确保列的顺序一致
    input_df_encoded = input_df_encoded[X_train.columns]

    # 进行预测
    predicted_price = model.predict(input_df_encoded)
    return predicted_price[0]


# 示例输入
input_data = {
    '»§ÐÍ': '2ÊÒ2Ìü1ÎÀ',
    '½¨ÖþÃæ»ý': 104.66,
    '³¯Ïò': 'ÄÏ',
    'Â¥²ã': '¸ß²ã',
    '×°ÐÞ': 'Ã«Å÷',
    '½¨ÖþÄê´ú': '2020Äê',
    'µçÌÝ': 'ÓÐ',
    '²úÈ¨ÐÔÖÊ': 'ÉÌÆ··¿',
    'ÇøÓò': '³Ç¹Ø',
    'Ñ§Ð£': 0
}

# 预测价格
predicted_price = predict_price(model, input_data)
print(f'预测价格: {predicted_price}')
